package com.cn.wanxi.message.controller;

import com.cn.wanxi.message.domain.MessageModel;
import com.cn.wanxi.message.domain.Result;
import com.cn.wanxi.message.socketserver.WebSocketServer;
import com.cn.wanxi.message.utils.ParamNameUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author JiJiang
 * @Date 2022/10/7 21:13
 * @Version 1.0
 */

@RestController
@CrossOrigin
public class LoginController {


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(String username, String password) {

        //根据用户获取其密码
        Object inRedisPassword = redisTemplate.opsForValue().get(ParamNameUtil.REDIS_REGISTERED_USER_NAME + username);

        //用户不存在
        if (Objects.isNull(inRedisPassword)) {

            return Result.getResult("error-NoThisUser");
        }

        inRedisPassword = inRedisPassword.toString();
        //密码不对应
        if (!inRedisPassword.equals(password)) {

            return Result.getResult("error-password");
        }

        //如果角色已经登录
        if (!Objects.isNull(redisTemplate.opsForValue().get(ParamNameUtil.REDIS_LOGIN_USER_NAME + username))) {
            return Result.getResult("error-UserHasLogin");
        }


        //将该用户标记为已经登录
        redisTemplate.opsForValue().set(ParamNameUtil.REDIS_LOGIN_USER_NAME + username, password);

        return Result.getResult("success");

    }


    @PostMapping("/logout")
    public Result logout(String username) {
        //如果用户名为空，直接退出
        if (Strings.isEmpty(username)) {
            return Result.getResult("error-username is empty");
        }
        if (redisTemplate.hasKey(ParamNameUtil.REDIS_LOGIN_USER_NAME + username)) {
            //从redis中移除登录用户信息
            redisTemplate.delete(ParamNameUtil.REDIS_LOGIN_USER_NAME + username);


            MessageModel messageModel = new MessageModel();
            messageModel.setCode(1);
            messageModel.setPublisher("system");
            messageModel.setReceiver("all-online-user");
            messageModel.setMessage(username);
            //从将对应的websocket也移除
            WebSocketServer.removeOnlineUser(username);

            return Result.getResult("success");
        }
        return Result.getResult("error-username not in redis");
    }

}
